# 构建阶段
FROM node:18-alpine AS builder

# 安装指定版本的 pnpm
RUN npm install -g pnpm@9.1.0

# 设置工作目录
WORKDIR /money-tracker

# 复制 package.json 和 pnpm-lock.yaml
COPY package.json pnpm-lock.yaml ./

# 设置 pnpm 镜像源并安装依赖
RUN pnpm config set registry https://registry.npmmirror.com && \
    pnpm install --frozen-lockfile

# 复制源代码
COPY . .

# 构建应用
RUN pnpm build

# 生产阶段
FROM node:18-alpine

# 安装指定版本的 pnpm
RUN npm install -g pnpm@9.1.0

# 设置工作目录
WORKDIR /money-tracker

# 设置环境变量
ENV NODE_ENV=production
ENV TZ=Asia/Shanghai

# 复制 package.json 和 pnpm-lock.yaml
COPY package.json pnpm-lock.yaml ./

# 安装生产环境依赖
RUN pnpm config set registry https://registry.npmmirror.com && \
    pnpm install --production --frozen-lockfile

# 从构建阶段复制编译后的文件和配置
COPY --from=builder /money-tracker/dist ./dist
COPY --from=builder /money-tracker/package.json ./
COPY --from=builder /money-tracker/tsconfig.json ./
COPY --from=builder /money-tracker/config ./config
COPY --from=builder /money-tracker/migrations ./migrations

# 创建非 root 用户
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
USER appuser

# 暴露端口
EXPOSE 3000

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1

# 启动命令
CMD ["node", "-r", "tsconfig-paths/register", "dist/app.js"] 